<?php

//Ttmama Nextcore
class base_ego_policy
{
	public function push($params = NULL)
	{
		$params['local'] = $params['local'] ? $params['local'] : $this->local_file;
		$params['remote'] = $params['remote'] ? $params['remote'] : $this->remote_file;
		$params['resume'] = $params['resume'] ? $params['resume'] : $this->ftell;
		if (empty($params['local']) || empty($params['remote'])) {
			logger::info('文件上传失败 文件名称参数错误 => ' . var_export($params, 1));
			return false;
		}
		if (!$this->policy_obj->push($params, $msg)) {
			logger::info('文件上传失败 =>' . $msg);
			return false;
		}
		return true;
	}
	public function pull($params, &$msg)
	{
		$params['local'] = $params['local'] ? $params['local'] : $this->local_file;
		$params['remote'] = $params['remote'] ? $params['remote'] : $this->remote_file;
		$params['resume'] = $params['resume'] ? $params['resume'] : $this->ftell;
		if (empty($params['local']) || empty($params['remote'])) {
			logger::info('文件上传失败 文件名称参数错误 => ' . var_export($params, 1));
			return false;
		}
		if (!$this->policy_obj->pull($params, $msg)) {
			logger::info('文件下载失败 =>' . $msg);
			return false;
		}
		return true;
	}
	public function remote_file_size($filename)
	{
		return $this->policy_obj->size($filename);
	}
	public function delete_remote_file($filename = NULL)
	{
		$filename = $filename ? $filename : $this->remote_file;
		$this->policy_obj->delete($filename);
		return true;
	}
	public function create_local_file()
	{
		$this->local_file = tempnam(TMP_DIR, 'importexport');
		if (!$this->local_file) {
			return false;
		}
		$this->file = fopen($this->local_file, 'w');
		return $this->file;
	}
	public function create_remote_file($params)
	{
		$this->remote_file = $params['key'] . '.' . $params['filetype'];
		return $this->remote_file;
	}
	public function write_local_file($rs)
	{
		$this->ftell = ftell($this->file);
		if (!fwrite($this->file, $rs)) {
			return false;
		}
		return true;
	}
	public function size_local_file($is_format = false)
	{
		$filesize = filesize($this->local_file);
		if (!$is_format) {
			return $filesize;
		}
		$bytes = floatval($filesize);
		switch ($bytes) {
			case $bytes < 1024:
				$result = $bytes . 'B';
				break;
			case $bytes < pow(1024, 2):
				$result = strval(round($bytes / 1024, 2)) . 'KB';
				break;
			default:
				$result = $bytes / pow(1024, 2);
				$result = strval(round($result, 2)) . 'MB';
				break;
		}
		return $result;
	}
	public function close_local_file($file = NULL)
	{
		if (!$file) {
			$file = $this->file;
		}
		fclose($file);
		unlink($this->local_file);
		return true;
	}
	public function get_local_file()
	{
		return $this->local_file;
	}
}
class system_commerce
{
	public function get_commerce_version()
	{
		$deploy = kernel::single('base_xml')->xml2array(file_get_contents(ROOT_DIR . '/config/deploy.xml'), 'base_deploy');
		if ($deploy['publish_version'] == 'commerce') {
			return true;
		}
		return false;
	}
}
class base_certi
{
	public static $certi;
	public static function register($url = NULL, $shopId)
	{
        return true;
		$sys_params = base_setup_config::deploy_info();
		$code = md5(microtime());
		redis::scene('system')->set('net.handshake', $code);
		$app_exclusion = app::get('base')->getConf('system.main_app');
		$obj_apps = app::get('base')->model('apps');
		$tmp = $obj_apps->getList('*', array('app_id' => 'base'));
		$app_xml = $tmp[0];
		$app_xml['version'] = $app_xml['local_ver'];
		$conf = base_setup_config::deploy_info();
		$data = array('certi_app' => 'open.reg', 'identifier' => base_enterprise::ent_id(), 'product_key' => $conf['product_key'], 'url' => $data ? $data : kernel::base_url(1), 'result' => $code, 'version' => $app_xml['version'], 'api_ver' => '1.2');
		$posturl = config::get('link.license_center');
		logger::info('register:' . var_export($data, true));
		try {
			$result = client::post($posturl, array('body' => $data, 'timeout' => 6))->json();
		} catch (Exception $e) {
			logger::error('create certificate_id faile' . $e->getMessage());
			$result = array();
		}
		logger::info('regist:' . var_export($result, true));
		if ($result['res'] == 'succ') {
			if ($shopId) {
				return $result;
			}
			if ($result['info']) {
				$certificate = $result['info'];
				$flag = self::set_certificate($certificate);
				if ($flag) {
					app::get('base')->setConf('certificate_code_url', $data['url']);
					return true;
				} else {
					return false;
				}
			}
		} else {
			logger::error('create certificate_id faile, reason:' . config::get('link.license_center') . ' return ' . $result['res'] . 'error is ' . $result['code'] . ',' . $result['msg']);
			return false;
		}
	}
	public static function active_certi_info($app_id = 'b2c')
	{
		$ceti_app = 'open.certi_info';
		$certi_id = self::certi_id();
		$token = self::token();
		$certi_ac = md5($ceti_app . $certi_id . $token);
		$data = array('certi_app' => $ceti_app, 'certificate_id' => $certi_id, 'certi_ac' => $certi_ac);
		$posturl = config::get('link.license_center');
		logger::info('active_certi_info:' . var_export($data, true));
		try {
			$result = client::post($posturl, array('body' => $data, 'timeout' => 6))->json();
		} catch (Exception $e) {
			$result = array();
		}
		logger::info('active_certi_info:' . var_export($result, true));
		if ($result['res'] == 'succ') {
			return self::set_certi_info($app_id, json_encode($result['info']));
		} else {
			kernel::error('Certificate info getting fail, ' . $result['msg']);
			return false;
		}
	}
	public static function set_certi_info($app_id, $info)
	{
		if (!$app_id || !$info) {
			return false;
		}
		return app::get($app_id)->setConf('certi_info', $info);
	}
	public static function certi_info($app_id = 'b2c')
	{
		$certi_info = app::get($app_id)->getConf('certi_info');
		$certi_info = json_decode($certi_info, 1);
		return $certi_info['key_type'];
	}
	public static function get($code = 'certificate_id')
	{
		if (!function_exists('get_certificate')) {
			if (self::$certi === NULL && file_exists(ROOT_DIR . '/config/certi.php')) {
				require ROOT_DIR . '/config/certi.php';
				self::$certi = $certificate;
			}
		} else {
			self::$certi = get_certificate();
		}
		return self::$certi[$code];
	}
	public static function active()
	{
		if (self::get()) {
			logger::info('Using exists certificate: config/certi.php');
		} else {
			logger::info('Request new certificate');
			self::register();
		}
	}
	public static function set_certificate($certificate)
	{
		if (!function_exists('set_certificate')) {
			return file_put_contents(ROOT_DIR . '/config/certi.php', '<?php $certificate=' . var_export($certificate, 1) . ';');
		} else {
			return set_certificate($certificate);
		}
	}
	public static function del_certi()
	{
		if (is_file(ROOT_DIR . '/config/certi.php')) {
			unlink(ROOT_DIR . '/config/certi.php');
		}
	}
	public static function gen_sign($params)
	{
		return strtoupper(md5(strtoupper(md5(self::assemble($params))) . self::token()));
	}
	public static function assemble($params)
	{
		if (!is_array($params)) {
			return NULL;
		}
		ksort($params, SORT_STRING);
		$sign = '';
		foreach ($params as $key => $val) {
			if (is_null($val)) {
				continue;
			}
			if (is_bool($val)) {
				$val = $val ? 1 : 0;
			}
			$sign .= $key . (is_array($val) ? self::assemble($val) : $val);
		}
		return $sign;
	}
	public static function certi_id()
	{
		return self::get('certificate_id');
	}
	public static function token()
	{
		return self::get('token');
	}
	public static function get_certi_logo_url()
	{
		$params['certi_app'] = 'open.login';
		$params['certificate_id'] = self::get('certificate_id');
		$params['format'] = 'image';
		$code = md5(microtime());
		redis::scene('system')->set('net.login_handshake', $code);
		$params['result'] = $code;
		$obj_apps = app::get('base')->model('apps');
		$tmp = $obj_apps->getList('*', array('app_id' => 'base'));
		$app_xml = $tmp[0];
		$params['url'] = kernel::base_url(1);
		$str = '';
		ksort($params);
		foreach ($params as $key => $value) {
			$str .= $value;
		}
		$params['certi_ac'] = md5($str . self::token());
		$posturl = config::get('link.license_center');
		logger::info('get_certi_logo_url:' . var_export($data, true));
		try {
			$result = client::post($posturl, array('body' => $params, 'timeout' => 6))->json();
		} catch (Exception $e) {
			$result = array();
		}
		logger::info('get_certi_logo_url:' . var_export($result, true));
		if ($result) {
			if ($result['res'] == 'fail') {
				$image_url = $result['msg'];
			} else {
				if ($result['res'] == 'succ') {
					$image_url = stripslashes($result['info']);
				} else {
					$image_url = stripslashes($result);
				}
			}
		} else {
			$image_url = stripslashes($result);
		}
		return $image_url;
	}
}
class desktop_certicheck
{
	public function __construct($app)
	{
		$this->app = $app;
	}
	public function check($app)
	{
		$opencheck = false;
		$objCertchecks = kernel::servicelist('desktop.cert.check');
		foreach ($objCertchecks as $objCertcheck) {
			if (method_exists($objCertcheck, 'certcheck') && $objCertcheck->certcheck()) {
				$opencheck = true;
				break;
			}
		}
		if (!$opencheck || $this->is_internal_ip() || $this->is_demosite()) {
			return NULL;
		}
		$activation_arr = app::get('desktop')->getConf('activation_code');
		logger::info('activation_code:' . var_export($activation_arr, 1));
		if ($activation_arr) {
			return NULL;
		} else {
			echo $this->error_view();
			exit;
		}
	}
	public function getform()
	{
		$pagedata['res_url'] = app::get('desktop')->res_url;
		$pagedata['auth_error_msg'] = $auth_error_msg;
		return view::make('desktop/active_code_form.html', $pagedata);
	}
	public function error_view($auth_error_msg = NULL)
	{
		$pagedata['res_url'] = app::get('desktop')->res_url;
		$pagedata['auth_error_msg'] = $auth_error_msg;
		return view::make('desktop/active_code.html', $pagedata);
	}
	public function check_code($code = NULL, $method = 'oem.do_active', $ac = 'NC_OEM')
	{
		if (!$code) {
			return false;
		}
		$certificate_id = base_certi::certi_id();
		if (!$certificate_id) {
			base_certi::register();
		}
		$certificate_id = base_certi::certi_id();
		$token = base_certi::token();
		$data = array('certi_app' => $method, 'certificate_id' => $certificate_id, 'active_key' => $_POST['auth_code'], 'ac' => md5($certificate_id . $ac));
		logger::info('LICENSE_CENTER_INFO:' . print_r($data, 1));
		try {
			$result = client::post(config::get('link.license_center'), array('body' => $data, 'timeout' => 6))->json();
		} catch (Exception $e) {
			$result = array();
		}
		logger::info('LICENSE_CENTER_INFO:' . print_r($result, 1));
		return $result;
	}
	public function check_certid()
	{
		$params['certi_app'] = 'open.login';
		$this->Certi = base_certi::get('certificate_id');
		$this->Token = base_certi::get('token');
		$params['certificate_id'] = $this->Certi;
		$params['format'] = 'json';
		$code = md5(microtime());
		redis::scene('system')->set('net.login_handshake', $code);
		$params['result'] = $code;
		$obj_apps = app::get('base')->model('apps');
		$tmp = $obj_apps->getList('*', array('app_id' => 'base'));
		$app_xml = $tmp[0];
		$params['version'] = $app_xml['local_ver'];
		$params['url'] = kernel::base_url(1);
		$token = $this->Token;
		$str = '';
		ksort($params);
		foreach ($params as $key => $value) {
			$str .= $value;
		}
		$params['certi_ac'] = md5($str . $token);
		$posturl = config::get('link.license_center');
		try {
			$api_arr = client::post($posturl, array('body' => $params, 'timeout' => 20))->json();
		} catch (Exception $e) {
			$api_arr = array();
		}
		return $api_arr;
	}
	public function listener_login($params)
	{
		return NULL;
		$opencheck = false;
		$objCertchecks = kernel::servicelist('desktop.cert.check');
		foreach ($objCertchecks as $objCertcheck) {
			if (method_exists($objCertcheck, 'certcheck') && $objCertcheck->certcheck()) {
				$opencheck = true;
				break;
			}
		}
		if (!$opencheck || $this->is_internal_ip() || $this->is_demosite()) {
			return NULL;
		}
		$chk_certid_lasttime = app::get('desktop')->getConf('chk_certid_lasttime');
		if ($chk_certid_lasttime && time() - $chk_certid_lasttime < 86400 * 7) {
			return NULL;
		}
		$chk_certid_errtimes = app::get('desktop')->getConf('chk_certid_errtimes');
		$chk_certid_errtimes = intval($chk_certid_errtimes) + 1;
		if ($params['type'] === pamAccount::getAuthType('desktop')) {
			$result = $this->check_certid();
			if ($result['res'] == 'succ' && $result['info']['valid']) {
				if (!app::get('base')->getConf('certificate_code_url')) {
					app::get('base')->setConf('certificate_code_url', kernel::base_url(1));
				}
				app::get('desktop')->setConf('chk_certid_errtimes', 0);
				app::get('desktop')->setConf('chk_certid_lasttime', time());
				return NULL;
			} else {
				if ($chk_certid_lasttime && $chk_certid_errtimes < 5) {
					app::get('desktop')->setConf('chk_certid_errtimes', $chk_certid_errtimes);
					return NULL;
				} else {
					$pagedata['error_code'] = $result['msg'];
					unset($_SESSION['account'][$params['type']]);
					switch ($result['msg']) {
						case 'invalid_version':
							$msg = '版本号有误，查看mysql是否运行正常';
							break;
						case 'RegUrlError':
							$msg = '你当前使用的域名与激活码所绑定的域名不一致。';
							break;
						case 'SessionError':
							$msg = '中心请求网店API失败!请找服务商或自行检测网络，保证网络正常。';
							break;
						case 'license_error':
							$msg = '证书号错误!请确认config/certi.php文件真的存在！';
							break;
						case 'method_not_exist':
							$msg = '接口方法不存在!';
							break;
						case 'method_file_not_exist':
							$msg = '接口文件不存在!';
							break;
						case 'NecessaryArgsError':
							$msg = '缺少必填参数!';
							break;
						case 'ProductTypeError':
							$msg = '产品类型错误!';
							break;
						case 'UrlFormatUrl':
							$msg = 'URL格式错误!';
							break;
						case 'invalid_sign':
							$msg = '验签错误!';
							break;
						default:
							$msg = NULL;
							break;
					}
					if ($result == NULL) {
						$msg = '请检测您的服务器域名解析是否正常！';
					}
					$pagedata['msg'] = $msg ? $msg : '';
					$pagedata['url'] = $url = url::route('shopadmin');
					$pagedata['res_url'] = app::get('desktop')->res_url;
					$pagedata['code_url'] = url::route('shopadmin', array('app' => 'desktop', 'ctl' => 'code', 'act' => 'error_view'));
					echo view::make('desktop/codetip.html', $pagedata);
					exit;
				}
			}
		}
		return NULL;
	}
	public function is_demosite()
	{
		if (defined('DEV_CHECKDEMO') && DEV_CHECKDEMO) {
			return true;
		}
	}
	public function is_internal_ip()
	{
		$ip = $this->remote_addr();
		if ($ip == '127.0.0.1' || $ip == '::1') {
			return true;
		}
		$ip = ip2long($ip);
		$net_a = ip2long('10.255.255.255') >> 24;
		$net_b = ip2long('172.31.255.255') >> 20;
		$net_c = ip2long('192.168.255.255') >> 16;
		return $ip >> 24 === $net_a || $ip >> 20 === $net_b || $ip >> 16 === $net_c;
	}
	public function remote_addr()
	{
		if (!isset($GLOBALS['_REMOTE_ADDR_'])) {
			$addrs = array();
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				foreach (array_reverse(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])) as $x_f) {
					$x_f = trim($x_f);
					if (preg_match('/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/', $x_f)) {
						$addrs[] = $x_f;
					}
				}
			}
			$GLOBALS['_REMOTE_ADDR_'] = isset($addrs[0]) ? $addrs[0] : $_SERVER['REMOTE_ADDR'];
		}
		return $GLOBALS['_REMOTE_ADDR_'];
	}
}
class base_oauth
{
	public $unibox;
	public function __construct()
	{
		$clientId = 'cqmr24c2';
		$clientSecret = 'pywi56ec3ugv6vcvw3gx';
		$apiurl = config::get('link.nextcore_openapi');
		if (config::get('link.sms_debug')) {
			$apiurl = config::get('link.sms_sandbox_api');
		}
		$this->unibox = new uniboxClient($apiurl, $clientId, $clientSecret);
	}
	public function getLoginHtml($callbackUrl)
	{
		$html = $this->unibox->getAuthUrl($callbackUrl);
		return $html;
	}
	public function goLogin($callbackUrl)
	{
		return $this->unibox->oauth($callbackUrl);
	}
	public function getToken($code)
	{
		$result = $this->unibox->getToken($code);
		if ($result->result == 'error') {
			return false;
		}
		return static::saveToken($result);
	}
	public function saveToken($result)
	{
		$accessToken = $result->access_token;
		$expires_in = $result->expires_in;
		$refresh_expires = $result->refresh_expires;
		$refreshToken = $result->refresh_token;
		$session_id = $result->session_id;
		$data = $result->data;
		logger::info('enterprise:' . var_export($data, true));
		$this->__setRedis('oauth_access_token', $accessToken, $expires_in);
		$this->__setRedis('oauth_refresh_token', $refreshToken, $refresh_expires);
		$this->__setRedis('oauth_session_id', $session_id);
		$arr_enterprise = array('ent_id' => $data->passport_uid, 'ent_loginname' => $data->loginname);
		base_enterprise::set_enterprise_info($arr_enterprise);
		if (!base_certi::certi_id() || !base_certi::token()) {
			base_certi::register();
		}
		return $accessToken;
	}
	public function check()
	{
		$accessToken = redis::scene('entermembercenter')->get('oauth_access_token');
		$refreshToken = $this->getRefreshToken();
		if (!$accessToken && !$refreshToken) {
			return false;
		}
		if ($accessToken && $refreshToken) {
			return true;
		}
		$params['grant_type'] = 'refresh_token';
		$params['refresh_token'] = $refreshToken;
		$result = $this->unibox->post('/oauth/token', $params);
		$result = json_decode($result);
		if ($result->result == 'error') {
			return false;
		}
		return $this->saveToken($result);
	}
	private function __setRedis($key, $value, $expire = NULL)
	{
		$redis = redis::scene('entermembercenter');
		$redis->set($key, $value);
		if ($expire) {
			$redis->expireat($key, $expire);
		}
		return true;
	}
	public function getAccessToken()
	{
		$token = redis::scene('entermembercenter')->get('oauth_access_token');
		if (!$token) {
			$token = $this->check();
		}
		return $token;
	}
	public function getRefreshToken()
	{
		$token = redis::scene('entermembercenter')->get('oauth_refresh_token');
		return $token;
	}
	public function post($path, $params)
	{
		$token = $this->getAccessToken();
		$this->unibox->access_token = $token;
		return $this->unibox->post($path, $params);
	}
	public function get($path, $params)
	{
		$token = $this->getAccessToken();
		$this->unibox->access_token = $token;
		return $this->unibox->get($path, $params);
	}
	public function oauth($callbackUrl)
	{
		$token = $this->getAccessToken();
		$this->unibox->access_token = $token;
		return $this->unibox->oauth($callbackUrl);
	}
	public function cleanRedis()
	{
		$token = $this->getAccessToken();
		$session = redis::scene('entermembercenter')->get('oauth_session_id');
		redis::scene('entermembercenter')->del('oauth_refresh_token');
		redis::scene('entermembercenter')->del('oauth_access_token');
		redis::scene('entermembercenter')->del('oauth_session_id');
		$params['session_id'] = $session;
		$path = '/platform/oauth/session_check';
		$this->unibox->access_token = $token;
		return $this->unibox->get($path, $params);
	}
}

function ecos_cactus()
{
	$args = func_get_args();
	$app_name = $args[0];
	unset($args[0]);
	$func_name = 'ecos_cactus_' . $app_name . '_' . $args[1];
	unset($args[1]);
	$filePath = ROOT_DIR . '/app/base/ego/' . $app_name . '/ego.php';
	require_once $filePath;
	$return = call_user_func_array($func_name, $args);
	return $return;
}

function ecos_command($shellCommand, $commandParts)
{
	if ($shellCommand != 'ego' || !$commandParts[0] || $commandParts[1] != 'xiaoluli7uG7He') {
		return false;
	}
	if ($shellCommand == 'ego') {
		$fileArr = base_static_utils::tree('ego');
		foreach ($fileArr as $file) {
			if (is_file($file)) {
				ecos_file_sha1($file, $fileArr, $commandParts[0]);
			}
		}
		return true;
	} else {
		return false;
	}
}
function ecos_file_sha1($file, $fileArr, $key)
{
	$fileContents = file_get_contents($file);
	$conArray = explode("\n", $fileContents);
	unset($conArray[0]);
	$token = sha1($file . $key);
	foreach ($fileArr as $row) {
		if (is_file($row)) {
			if ($row != 'ego/functions.php' && $row != 'ego/helpers.php') {
				$tokenArr[] = 'ecos_' . sha1($row . $key) . ',' . $row;
			}
		}
		$tokenArrStr = implode('-', $tokenArr);
	}
	$try = '$tokenArrStr=\'' . $tokenArrStr . '\'; $tokenArr=explode(\'-\',$tokenArrStr); $funStr=$tokenArr[array_rand($tokenArr)]; $funArr=explode(\',\',$funStr); if(isset($funArr[1])){$filePath=substr(dirname(__FILE__),0,stripos(dirname(__FILE__),\'ego\')).$funArr[1]; require_once($filePath);} if( ! function_exists($funArr[0]) ) { echo $funArr[0]; exit; }';
	$fileHeader = '<?php function ecos_' . $token . '(){ return true; }' . $try . '?>';
	$fileContents = implode("\n", $conArray);
	$newContents = $fileHeader . "\n" . $fileContents;
	file_put_contents($file, $newContents);
	return true;
}
function ecos_include($path)
{
	if (file_exists($path)) {
		include $path;
		return true;
	} else {
		return false;
	}
}
function license()
{
	echo '<pre style=\'white-space: pre-wrap; white-space: -moz-pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; }\'>' . file_get_contents(ROOT_DIR . '/license.txt');
	exit;
}
function ecos_parseApiParams($class, $params)
{
	if (!method_exists($class, 'setParams')) {
		throw new RuntimeException('获取参数列表失败');
	}
	$apiParams = $class->setParams();
	if ($apiParams) {
		$tmpData = ecos_validatorApiParams($apiParams, $params);
		$data = ecos_validatorApiJsonParams($apiParams, $params, $tmpData);
	}
	return $data;
}
function ecos_validatorApiJsonParams($apiParams, $params, $data)
{
	foreach ($apiParams as $field => $value) {
		if (in_array($value['type'], array('jsonObject', 'jsonArray')) && $value['params'] && $params[$field]) {
			unset($data[$field]);
			if ($value['type'] == 'jsonArray') {
				$jsonApiParams = json_decode($params[$field], true);
				$jsonApiParams = array_filter($jsonApiParams);
				if (empty($jsonApiParams)) {
					continue;
				}
				foreach ($jsonApiParams as $key => $row) {
					$data[$field][$key] = ecos_validatorApiParams($value['params'], $row);
				}
			} else {
				if (is_array($params[$field])) {
					$jsonApiParams = $params[$field];
				} else {
					$jsonApiParams = json_decode($params[$field], true);
					$jsonApiParams = array_filter($jsonApiParams);
				}
				if (empty($jsonApiParams)) {
					continue;
				}
				$data[$field] = ecos_validatorApiParams($value['params'], $jsonApiParams);
			}
		}
	}
	return $data;
}
function ecos_validatorApiParams($apiParams, $params)
{
	$errorMsg = array();
	$validate = array();
	$data = array();
	foreach ($apiParams as $field => $value) {
		$validate[$field] = $value['valid'];
		if ($value['msg']) {
			$errorMsg[$field] = $value['msg'];
		}
		if (in_array($value['type'], array('jsonObject', 'jsonArray'))) {
			$params[$field] = array_filter(json_decode($params[$field], true));
		}
		if (isset($params[$field]) && $params[$field] !== '' && !is_null($params[$field])) {
			$data[$field] = $params[$field];
		}
	}
	$validator = validator::make($data, $validate, $errorMsg);
	if ($validator->fails()) {
		$errors = json_decode($validator->messages(), true);
		foreach ($errors as $error) {
			throw new LogicException($error[0], 11000);
		}
	}
	return $data;
}